package de.preisrobot.persistence.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import de.preisrobot.entity.ArtikelProperty;

@Repository
public class ArtikelPropertyDaoImpl implements ArtikelPropertyDao
{
   private static Logger log = Logger.getLogger(ArtikelPropertyDaoImpl.class);
   
   private static final String ARTIKEL2PROPERTY_TABLE = ArtikelProperty.class.getSimpleName();
   
   @PersistenceContext
   EntityManager em;

   @Override
   @Transactional(propagation = Propagation.REQUIRES_NEW)
   public long save(ArtikelProperty p)
   {
      em.persist(p);
      return p.getId();
   }
   
   
   @Override
   @Transactional(propagation = Propagation.REQUIRES_NEW)
   public void saveNeu(Object p)
   {
      em.persist(p);
 
   }
   

   @Override
   @Transactional(propagation=Propagation.REQUIRES_NEW)
   public ArtikelProperty find(ArtikelProperty artikelProperty)
   {
      Query createQuery = em
         .createQuery("select p from ArtikelProperty p where p.hauptkategorie like ?1 and p.bezeichnung like ?2 and p.wert like ?3");
      createQuery.setParameter(1, artikelProperty.getHauptkategorie());
      createQuery.setParameter(2, artikelProperty.getBezeichnung());
      createQuery.setParameter(3, artikelProperty.getWert());
    
      try
      {
         List<?> resultList = createQuery.getResultList();
         if(! resultList.isEmpty())
          {Object singleResult = resultList.get(0);//createQuery.getSingleResult();
          return (ArtikelProperty) singleResult;
          }
          return null;
      }
      catch (Exception e)
      {
         log.warn(e.getMessage());
      }
      return null;
   }


   @Override
   @Transactional(propagation=Propagation.REQUIRES_NEW)
   public int delete(long artikelid)
   {
     Query nativeQuery = em.createNativeQuery("delete from  artikel2property where artikelid ="+artikelid);
     return nativeQuery.executeUpdate();   
   }

}
